﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Core
{
    public class AudioSystem : Core.Component, IAwake, IGameObject, IUpdate
    {
        public GameObject gameObject { get; private set; }
        public Transform transform { get; private set; }

        private readonly Stack<AudioObject> pool = new();
        private readonly Queue<AudioObject> playing = new();

        public void Awake()
        {
            gameObject = new GameObject($"{G.Name}_audio");
            transform = gameObject.transform;

            GameObject.DontDestroyOnLoad(gameObject);
        }

        public AudioObject Pop()
        {
            return pool.Count > 0 ? pool.Pop() : G.Factory.Create<AudioObject>();
        }

        public void Push(AudioObject obj)
        {
            obj.LastUseTime = Time.realtimeSinceStartup;
            pool.Push(obj);
        }

        public void Update()
        {
            //if (q_waiting.Count > 0)
            //{
            //    var node = q_waiting.Dequeue();

            //    var audioObj = Pop();
            //    audioObj.SetRes(node.Res);
            //    node.Func?.Invoke(audioObj);
            //    audioObj.Start();
            //    q_playing.Enqueue(audioObj);
            //}

            var cnt = playing.Count;
            for (int i = 0; i < cnt; i++)
            {
                var element = playing.Dequeue();
                if (element.IsComplete == false)
                {
                    playing.Enqueue(element);
                    continue;
                }

                element.Stop();
                Push(element);
            }
        }

        public void Play(string res, Action<AudioObject> func = null)
        {
            if (string.IsNullOrEmpty(res)) return;

            //q_waiting.Enqueue(new Node() { Res = res, Func = func });

            var audioObj = Pop();
            audioObj.SetRes(res);
            func?.Invoke(audioObj);
            audioObj.Start();
            playing.Enqueue(audioObj);
        }
    }
}
